import FreeSimpleGUI as sg
from pynput.keyboard import Controller
import pygetwindow as gw
from io import StringIO
from time import sleep
import threading
def send2key(window_title,text):
    global running,key_delay
    keyboard=Controller()
    windows=gw.getWindowsWithTitle(window_title)
    w:gw.Win32Window=windows[0]
    s=StringIO(text)
    while running:
        line=s.readline()
        if line=='':break
        for k in line:
            if not w.isActive:
                w.activate()
            keyboard.type(k)
            sleep(key_delay)
    return


key_delay=0.1
running=False
def main():
    global running,key_delay
    keyboard=Controller()
    keyboard.pressed()
    layout = [[sg.Text('select window to send:')],
              [sg.Listbox(values=[ele for ele in gw.getAllTitles() if len(ele)>0],
                          key="-SendWindow-",
                          size=(80,5),
                          select_mode='LISTBOX_SELECT_MODE_BROWSE',highlight_background_color='red',highlight_text_color='black')],
              [sg.Text('Send text:')],
              [sg.Multiline(size=(80,40), key='-MLINE-', autoscroll=True)],

              [sg.Button('Go'), sg.Button('Exit'),sg.Text('Delay(s):'),sg.Slider(
                  key='-delay-',
                  range=(0.0,2),
                  default_value=key_delay,
                  resolution=0.01,
                  orientation='h',
                  enable_events=True,
                  border_width=1,
                  size=(30,10),
                  tick_interval=0.3),
                  ]]

    window = sg.Window('Paste2keyboard', layout, keep_on_top=True, resizable=True, finalize=True)
    d=False
    while True:             # Event Loop
        event, values = window.read()
        if event == sg.WIN_CLOSED or event == 'Exit':
            print(values)
            break
        if event == '-delay-':
            print("delay:{}s".format(values['-delay-']))
            key_delay=values['-delay-']
        # This is the important bit of code. It sets the current contents of the multiline to be the correct justification
        if event == 'Go':
            if len(values['-SendWindow-'])==0:
                sg.popup("必须选一个进程",keep_on_top=True)
                continue
            if len(values['-MLINE-'])==0:
                sg.popup("写点啥吧",keep_on_top=True)
                continue

            d= not d
            print("pressed [GO]")
            print("select window:",len(values['-SendWindow-']),values['-SendWindow-'])
            print("text window:",len(values['-MLINE-']),values['-MLINE-'])
            window['-SendWindow-'].update(disabled=d)
            window['-MLINE-'].update(disabled=d)
            window.refresh()
            if window['Go'].ButtonText=='Go':
                window['Go'].update(text='Stop')
                running=True
                window.refresh()
                do_type_t=threading.Thread(target=send2key,args=(values['-SendWindow-'][0],values['-MLINE-']))
                do_type_t.start()
            else:
                running=False
                if do_type_t:
                    do_type_t.join()
                window['Go'].update(text='Go')
                window.refresh()
            
    window.close()


if __name__ == '__main__':
    main()
